package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

var HttpApi *http.Client

func init() {
	transport := &http.Transport{
		DisableKeepAlives: false,
	}

	HttpApi = &http.Client{Transport: transport}
}

func main() {
	var (
		line []byte
		//prefix bool
		obj *Obj
	)
	if len(os.Args) <= 1 {
		log.Println("ERROR: ./xxxxxx /xxx.log 启动监控模式。。")

	} else {
		go func() {

			path := os.Args[1]
			if file, err := os.Open(path); err == nil {
				defer file.Close()
				reader := bufio.NewReader(file)
				for {

					if line, _, err = reader.ReadLine(); err == nil {
						//log.Println(part, prefix, err)
						if obj = format(string(line)); obj != nil {
							if obj.typ == "query[A]" || obj.typ == "query[AAAA]" {
								if _, err := HttpApi.Get(fmt.Sprintf("http://192.168.0.20:22225/api/send?d=%s&ip=%s", obj.daemon, obj.ip)); err == nil {

								}
							}
						}
					} else if err != io.EOF {
						log.Println("ERROR:", err)
						return
					}
				}
			} else {
				log.Println(err)
			}
		}()
	}

	for {
		select {
		case s := <-sendChan:
			//fmt.Println(s)
			if _, ok := mm[s.ip]; !ok {
				mm[s.ip] = map[string]Send{}
			}
			mm[s.ip][s.d] = s
		case str := <-addhostChan:
			cmd(str)
		}
	}
}

type Obj struct {
	m      string
	d      string
	t      string
	label  string
	typ    string
	daemon string
	where  string
	ip     string
}

func format(line string) *Obj {
	aa := strings.Split(line, " ")
	if len(aa) == 8 {
		a := new(Obj)
		a.m = aa[0]
		a.d = aa[1]
		a.t = aa[2]
		a.label = aa[3]
		a.typ = aa[4]
		a.daemon = aa[5]
		a.where = aa[6]
		a.ip = aa[7]
		return a
	} else {
		return nil
	}
}
